package cn.xqj.system.service.impl;

import cn.xqj.org.mapper.EmployeeMapper;
import cn.xqj.system.domain.Role;
import cn.xqj.system.mapper.RoleMapper;
import cn.xqj.system.service.IRoleService;
import cn.xqj.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        addByRole(role);
    }


    @Override
    @Transactional
    public void update(Role role) {
        Long id = role.getId();
        delByRoleId(id);
        addByRole(role);
    }


    @Override
    @Transactional
    public void del(Long id) {
        delByRoleId(id);
        super.del(id);
    }

    public void delByRoleId(Long id) {
        roleMapper.delRoleMenu(id);
        roleMapper.delRolePermission(id);
        employeeMapper.delEmployeeRole(id);
    }

    public void addByRole(Role role) {
        Long roleId = role.getId();
        List<Long> menus = role.getMenus();
        if (menus.size() > 0) {
            roleMapper.addRoleMenu(roleId,menus);
        }
        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0) {
            roleMapper.addRolePermission(roleId,permissions);
        }
    }

    @Override
    public void patchDel(Long[] ids) {
        for (Long id : ids) {
            delByRoleId(id);
        }
        super.patchDel(ids);
    }
}
